package com.gserver.commons.resource.impl;

import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gserver.commons.PoiUtils;

public abstract class AbstractExcelResource extends AbstractResource {

	public AbstractExcelResource(String file) {
		this.file = file;
	}

	public void loadFromXls() {
		InputStream inp = null;
		logger.info((new StringBuilder(
				"\u5F00\u59CB\u52A0\u8F7D\u8D44\u6E90\u6587\u4EF6 ["))
				.append(file).append("] .").toString());
		try {
			inp = new FileInputStream(file);
			HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
			int sheets = wb.getNumberOfSheets();
			for (int i = 0; i < sheets; i++) {
				HSSFSheet sheet = wb.getSheetAt(i);
				String sheetName = wb.getSheetName(i);
				if (logger.isInfoEnabled())
					logger.info((new StringBuilder(
							"\u6B63\u5728\u52A0\u8F7D\u9875\u540D\u4E3A :"))
							.append(sheetName).toString());
				loaderPage(sheet, i);
			}
		} catch (Exception e) {
			throw new RuntimeException(
					"ERR.LOAD #GS.net.tour.mmo.gateway.resource.impl.abstractResource",
					e);
		} finally {
			IOUtils.closeQuietly(inp);
		}
		if (logger.isInfoEnabled())
			logger.info((new StringBuilder(
					"\u8D44\u6E90\u6587\u4EF6\u52A0\u8F7D\u5B8C\u6BD5 ["))
					.append(file).append("] .").toString());
		resources.put(getClass(), this);
		return;
	}

	public abstract void loaderPage(HSSFSheet hssfsheet, int i);

	public int getInt(HSSFRow row, int cellIndex) {
		return PoiUtils.getIntValue(row.getCell(cellIndex));
	}

	public float getFloat(HSSFRow row, int cellIndex) {
		return PoiUtils.getFloatValue(row.getCell(cellIndex));
	}

	public String getString(HSSFRow row, int cellIndex) {
		return PoiUtils.getStringValue(row.getCell(cellIndex));
	}

	public int[] getArray(HSSFRow row, int cellIndex) {
		String str = getString(row, cellIndex);
		if (str == null || str.isEmpty() || str.trim().length() < 0)
			return null;
		String ss[] = str.split(",");
		int arr[] = new int[ss.length];
		for (int i = 0; i < arr.length; i++)
			try {
				arr[i] = Integer.parseInt(ss[i]);
			} catch (Exception e) {
				if (logger.isErrorEnabled())
					logger.error(
							(new StringBuilder(
									"\u975E\u6570\u5B57\u8F6C\u6362\uFF1A"))
									.append(ss[i]).append("  ").append(row)
									.append("  \u884C\uFF1A").append(cellIndex)
									.toString(), e);
				throw new IllegalArgumentException(e);
			}

		return arr;
	}

	public static final Logger logger = LoggerFactory
			.getLogger(AbstractExcelResource.class);
	protected final String file;
}
